package com.music.authority.dao.impl;

import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.music.authority.dao.UpMusicDao;
import com.music.domain.CateMusic;
import com.music.domain.Music;

/**
 * 实现类
 * @author LFSenior
 *
 */
@Repository
public class UpMusicDaoImpl implements UpMusicDao {
	@Autowired
	SessionFactory sessionFactory;

	@Override
	public void insertMusic(Map param) {
		String sql="SELECT ID FROM T_MUSIC_AUTHOR WHERE NAME=:NAME";
		Session session = sessionFactory.getCurrentSession();
		SQLQuery sqlQuery = session.createSQLQuery(sql);
		sqlQuery.setParameter("NAME", param.get("author"));
		List<String> data = sqlQuery.list();
		if(data!=null&&data.size()>0){
			param.put("authorid", data.get(0));
		}else{
			insertAuthor(param.get("id").toString(), param.get("author").toString());
			param.put("authorid", param.get("id"));
		}
		sql="INSERT INTO T_MUSIC(ID,NAME,AUTHORID,IMGURI,MUSICURI,CATEID,AUTHOR) VALUES("
				+ ":ID,:NAME,:AUTHORID,:IMGURI,:MUSICURI,:CATEID,:AUTHOR)";
		sqlQuery=session.createSQLQuery(sql);
		sqlQuery.setParameter("ID", param.get("id"));
		sqlQuery.setParameter("NAME", param.get("name"));
		sqlQuery.setParameter("AUTHORID", param.get("authorid"));
		sqlQuery.setParameter("IMGURI", param.get("imageURI"));
		sqlQuery.setParameter("MUSICURI", param.get("musicURI"));
		sqlQuery.setParameter("CATEID", param.get("cateid"));
		sqlQuery.setParameter("AUTHOR", param.get("author"));
		sqlQuery.executeUpdate();
	}

	@Override
	public void deleteMusic(String musicId) {
		Session session = sessionFactory.getCurrentSession();
		session.delete(session.get(Music.class, musicId));
	}
	
	public void insertAuthor(String id,String name){
		String sql="INSERT INTO T_MUSIC_AUTHOR(ID,NAME) VALUES(:ID,:NAME)";
		SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(sql);
		query.setParameter("ID", id);
		query.setParameter("NAME", name);
		query.executeUpdate();
	}

	@Override
	public List<CateMusic> findAllCate() {
		String hql="from CateMusic";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		List<CateMusic> data = query.list();
		return data;
	}

	@Override
	public List<Music> findAllMusic() {
		String hql="from Music";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		List<Music> data = query.list();
		return data;
	}
}
